package org.example.controller;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;

/**
 * @Author OY
 * @Date 2021/11/19
 */
@Controller
public class HelloController {

    /**
     * 无需登录就可以访问
     * @return
     */
    @ResponseBody
    @GetMapping(value = "/hello")
    public String hello(){
        return "hello";
    }

    @GetMapping(value = "/employees")
    public String employees(Model model, HttpSession session, @RequestParam(value = "token", required = false) String token) {
        if(!StringUtils.isEmpty(token)){
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> forEntity = restTemplate.getForEntity("http://127.0.0.1:8080/userinfo?token=" + token, String.class);
            String body = forEntity.getBody();

            session.setAttribute("loginUser",body);
        }

        Object logUser = session.getAttribute("loginUser");

        if(logUser == null){
            return "redirect:" + "http://127.0.0.1:8080/login.html"+"?redirect_url=http://127.0.0.1:8081/employees";
        }else{

            ArrayList<String> emps = new ArrayList<>();

            emps.add("张三");
            emps.add("李四");

            model.addAttribute("emps",emps);

            return "employees";
        }
    }
}